package cn.deschen.search.mysql;

import cn.deschen.search.mysql.config.BinlogProperties;
import cn.deschen.search.mysql.listeners.BinlogListener;
import com.github.shyiko.mysql.binlog.BinaryLogClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.IOException;

/**
 * @Author hanbin_chen
 * @Description mysql binlog客户端
 * @DateTime 2021/6/9
 * @Version V1.0.0
 */
@Slf4j
@Component
public class BinlogClient {

    private BinaryLogClient client;

    @Autowired
    private BinlogProperties properties;

    @Autowired
    private BinlogListener listener;

    @PostConstruct
    public void connect() {

        new Thread(() -> {
            client = new BinaryLogClient(
                    properties.getHost(),
                    properties.getPort(),
                    properties.getUsername(),
                    properties.getPassword()
            );

            if (!StringUtils.isEmpty(properties.getBinlogName()) &&
                    !properties.getPosition().equals(-1L)) {
                client.setBinlogFilename(properties.getBinlogName());
                client.setBinlogPosition(properties.getPosition());
            }

            client.registerEventListener(listener);

            try {
                log.info("BinlogClient start");
                /**
                 * 此处会阻塞，直到断开连接 </br>
                 * 因此为了不阻塞主线程，创建一个新线程创建binlog客户端
                 * {@link BinaryLogClient#disconnect()}
                 */
                client.connect();
                log.info("BinlogClient done");
            } catch (IOException ex) {
                ex.printStackTrace();
            }

        }).start();
    }

    @PreDestroy
    public void close() {
        try {
            client.disconnect();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
